package com.example.csupermaket.controller;


import com.example.csupermaket.exception.ServiceException;
import com.example.csupermaket.web.JsonResult;
import com.example.csupermaket.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;


/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult handleServiceException(ServiceException e) {
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,e.getMessage());
    }

    @ExceptionHandler
    public JsonResult handleBindException(BindException e) {
        //此方法在出现多个检查错误时只会随机出现一个
        //清除其他的不想要的内容
        String message = e.getFieldError().getDefaultMessage();
        return JsonResult.fail(ServiceCode.ERR_CONFLICT,message);

//        //此方法将会将所有检查错误列举出来
//        StringJoiner stringJoiner = new StringJoiner("，", "请求参数格式错误", "!!");
//        List<FieldError> fieldErrors = e.getFieldErrors();
//        for (FieldError fieldError : fieldErrors) {
//            stringJoiner.add(fieldError.getDefaultMessage());
//        }
//
//        return stringJoiner.toString();
    }

    @ExceptionHandler
    public String handleConstraintViolationException(ConstraintViolationException e) {
        String message = null;
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        for (ConstraintViolation<?> constraintViolation : constraintViolations) {
            //只会执行一次，但是set型，所以必须遍历
            message = constraintViolation.getMessage();
        }
        return message;
    }


    //避免项目出现500
    @ExceptionHandler
    public String ThrowableException(Throwable e) {
        String message = "服务器忙，请稍后再试，或联系系统管理员！";
        log.warn("异常类型：{}",e.getClass().getName());
        log.warn("异常信息：{}",e.getMessage());
        //使错误信息在控制台上显示
        //e.printStackTrace();
        return message;
    }
}
